import 'package:intl/intl.dart';

class LaraPressDate {
  static String formatToYMDHM(String date) {
    try {
      // 先替换空格为 T，避免 DateTime.parse 出错
      String fixed = date.replaceAll(" ", "T");
      DateTime inputDate = DateTime.parse(fixed);

      // 用 intl 包格式化
      final formatter = DateFormat("yyyy年MM月dd日 HH:mm");
      return formatter.format(inputDate);
    } catch (e) {
      return date;
    }
  }

  static String formatAgo(String date) {
    try {
      // 解析时间字符串
      DateTime inputDate = DateTime.parse(date);
      DateTime now = DateTime.now();
      Duration difference = now.difference(inputDate);

      // 如果时间在未来，返回"刚刚"
      if (difference.isNegative) {
        return "刚刚";
      }

      int totalSeconds = difference.inSeconds;
      int totalMinutes = difference.inMinutes;
      int totalHours = difference.inHours;
      int totalDays = difference.inDays;

      // 小于1小时
      if (totalHours < 1) {
        if (totalMinutes < 1) {
          return "$totalSeconds秒前";
        } else {
          return "$totalMinutes分钟前";
        }
      }
      // 1小时到1天
      else if (totalDays < 1) {
        return "${inputDate.hour.toString().padLeft(2, '0')}:${inputDate.minute.toString().padLeft(2, '0')}";
      }
      // 1个月到1年
      else if (totalDays < 365) {
        return "${inputDate.month}月${inputDate.day}日 ${inputDate.hour.toString().padLeft(2, '0')}:${inputDate.minute.toString().padLeft(2, '0')}";
      }
      // 超过1年
      else {
        return "${inputDate.year}年${inputDate.month}月${inputDate.day}日 ${inputDate.hour.toString().padLeft(2, '0')}:${inputDate.minute.toString().padLeft(2, '0')}";
      }
    } catch (e) {
      // 如果解析失败，返回原字符串
      return date;
    }
  }
}
